package controller;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;

import dal.JMLDatabase;
import dto.TableIconDTO;

public class DatabaseController {
	private String _databaseName;
	private JMLDatabase dao;

	public DatabaseController(String _databaseName)
			throws UnknownHostException, IOException {
		super();
		this._databaseName = _databaseName;
		dao = new JMLDatabase();
	}

	/**
	 * connect to server
	 * 
	 * @param ip
	 *            string
	 * @param port
	 *            int
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public void connectToServer(String ip, int port)
			throws UnknownHostException, IOException {
		dao.connectToServer(ip, port);
	}

	/**
	 * login server with username and password
	 * 
	 * @param username
	 *            string
	 * @param password
	 *            string
	 * @return boolean true when log in successfully
	 * @throws Exception
	 */
	public boolean login(String username, String password) throws Exception {
		return dao.login(username, password);
	}

	/**
	 * Create database
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean createDatabase() throws Exception {
		if (!isValidDBName()) {
			throw new Exception("Database name is invalid");
		}
		return dao.createDatabse(_databaseName);
	}

	/**
	 * check database name is valid or not?
	 * 
	 * @return true if valid false if invalid.
	 */
	public boolean isValidDBName() {
		if (_databaseName.isEmpty()) {
			return false;
		}
		// replace black char with _ char
		_databaseName = _databaseName.replace(' ', '_');
		return true;
	}

	/**
	 * Drop database
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean dropDatabase() throws Exception {
		if (!isValidDBName()) {
			throw new Exception("Database name is invalid");
		}

		return dao.dropDatabase(_databaseName);
	}

	/**
	 * Get all table name of database
	 * 
	 * @return ArrayList<String>
	 * @throws Exception
	 */
	public ArrayList<TableIconDTO> getAllTableName() throws Exception {
		ArrayList<String> tables = dao.getAllTableName(this._databaseName);
		if (tables == null)
			return null;
		Collections.sort(tables);
		ArrayList<TableIconDTO> result = new ArrayList<>();
		for (String table : tables) {
			result.add(new TableIconDTO(table));
		}
		return result;
	}

	/**
	 * Set this to default database
	 * 
	 * @throws Exception
	 */
	public void setAsDefault() throws Exception {
		if (!isValidDBName()) {
			throw new Exception("Database name is invalid");
		}
		ControllerConfiguration.DEFAULT_DATABASE = this._databaseName;
		System.out.println(ControllerConfiguration.DEFAULT_DATABASE);
	}

}
